/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mvc.example.presentation.model;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.event.EventListenerList;
import mvc.example.presentation.events.DataEvent;
import mvc.example.presentation.listeners.StudentDataListener;

/**
 *
 * @author zeta
 */
public class AbstractModel implements Model {
    
    protected PropertyChangeSupport propertyChangeSupport;

    protected EventListenerList listenerList;

    public AbstractModel() {
        this.propertyChangeSupport = new PropertyChangeSupport(this);
        this.listenerList = new EventListenerList();
    }

    @Override
    public void addDataListener(StudentDataListener l) {
        listenerList.add(StudentDataListener.class, l);
    }

    @Override
    public void removeDataListener(StudentDataListener l) {
        listenerList.remove(StudentDataListener.class, l);
    }
    
    protected void fireContentsChanged(Object source, int index0, int index1)
    {
        StudentDataListener[] listeners = listenerList.getListeners(StudentDataListener.class);
	DataEvent e = null;
        
        //asi recorre el array swing
	for (int i = 0; i < listeners.length ; i++) {
	   
		if (e == null) {
		    e = new DataEvent(source, DataEvent.CONTENTS_CHANGED, index0);
		}
		listeners[i].contentsChanged(e);
	           
	}
    }
    protected void fireIntervalAdded(StudentsModel aThis, int index) {
       StudentDataListener[] listeners = listenerList.getListeners(StudentDataListener.class);
	DataEvent e = null;
	for (int i = 0; i < listeners.length ; i++) {
		if (e == null) {
		    e = new DataEvent(aThis, DataEvent.NEW_DATA, index);
		}
                listeners[i].contentsChanged(e);
	}
    }
    
    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }

    protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
        propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue);
    }
  
}
